package org.dzq.designmode.interpreter;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @ClassName: Calculator
 * @Package: org.dzq.designmode.interpreter
 * @author: 越
 * @date: 2023/6/19 21:34
 * @Description: 计算器
 */
public class Calculator {

    private Expression expression;

    public Calculator(String expStr){
        Stack<Expression> stack = new Stack<>();
        char[] chars = expStr.toCharArray();
        Expression left = null;
        Expression right = null;
        for(int i = 0 ; i < chars.length ; i++){
            switch (chars[i]){
                case '+':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(chars[++i]));
                    stack.push(new AddExpression(left, right));
                    break;
                case '-':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(chars[++i]));
                    stack.push(new SubExpression(left, right));
                    break;
                default:
                    stack.push(new VarExpression(String.valueOf(chars[i])));
                    break;
            }
        }
        //栈中最后只会有一个表达式对象
        this.expression = stack.pop();
    }

    //计算表达式
    public int run(Map<String, Integer> var) {
        return this.expression.interpreter(var);
    }
}
